package netty.websocket;

import bobochat.service.UsersService;
import bobochat.util.JSONUtils;
import bobochat.util.SpringUtil;
import common.MsgActionEnum;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import netty.model.ChattingWrap;
import netty.model.UserChannelMap;
import org.springframework.context.ApplicationContext;

/**
 * @author shkstart
 * @create 2019-11-15 19:47
 */

public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    /**
     * 用来存放每个用户的channel
     */
    private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);


    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        String msg = textWebSocketFrame.text();
        System.out.println(msg);

        //json字符串转换为聊天封装对象
        ChattingWrap chattingWrap = JSONUtils.json2pojo(msg, ChattingWrap.class);

        Integer action = chattingWrap.getAction();

        if (action == MsgActionEnum.CONNECT.type) {
            //第一次连接
            //建立用户id与用户连接channel的联系
            String senderId =chattingWrap.getChattingMsg().getSenderId();//用户id
            Channel channel = channelHandlerContext.channel();//用户channel
            UserChannelMap.put(senderId, (java.nio.channels.Channel) channel);//userId与channel关系的建立

        } else if (action == MsgActionEnum.CHAT.type) {
            //用来发送聊天消息,1.把聊天记录保存到数据库，并将签收状态改为未签收

            //获取ApplicationContext对象
            ApplicationContext applicationContext = SpringUtil.getApplicationContext();

            //获取service对象的方法
            UsersService usersService = (UsersService) applicationContext.getBean("usersService");

            //2.发送消息
            //从全局变量channel关系中获取接收方的channel
//            Channel channel=UserChannelMap.get("接收方的userId");
//
//
//            //3.通过获取到的channel来发送给相应用户
//            channel.writeAndFlush();


        } else if (action == MsgActionEnum.SIGNED.type) {
            //进行消息签收，修改数据库签收状态改为已签收(批量签收）




        }else if (action==MsgActionEnum.KEEPALIVE.type) {
            System.out.println("进入心跳");
        }
        }

        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
            Channel channel = ctx.channel();
            channels.add(channel);
        }

}

